package com.conduit.comnands;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.commands.prototype.AbstractCommand;
import com.conduit.enums.ResultCode;

public class CopyFileCommand extends AbstractCommand {

	public CopyFileCommand() {
		// copy file <file location> <file destination>
		commandSyntax = "copy file\\s{2,}(.*)\\s{2,}(.*)";
	}

	@Override
	public void executeWithArgs(String args) {
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			String fileLocation = matcher.group(1);
			String saveAsFile = matcher.group(2);
			File fromfile = new File(fileLocation);
			File tofile = new File(saveAsFile);
			try {
				tofile.createNewFile();
				FileInputStream from = new FileInputStream(fromfile);
				FileOutputStream to = new FileOutputStream(tofile);
				byte[] buffer = new byte[4096];
				int bytesread;
				while ((bytesread = from.read(buffer)) != -1) {
					to.write(buffer, 0, bytesread);
				}
				Thread.sleep(1000);
				setResult("File Was Successesfuly Copied to " + saveAsFile);
				setResultCode(ResultCode.Successes);
			} catch (Exception e) {
				setResult(e.getMessage());
				setResultCode(ResultCode.Error);
			}
		}
	}
	public String getCommandName() {
		return "Copy File";
	}
}
